from flask import Blueprint, request
from flask_jwt_extended import jwt_required

from model.match_model import MatchModel
from service.match_service import MatchService

# 声明蓝图
match_router = Blueprint(name="match", import_name=__name__)
match_service = MatchService()


@match_router.route("/match/get")
@jwt_required()
def match_get():
    """
    查找
    {id: 1}
    :return:
    """
    # 获取请求参数
    data = request.args
    case_id = data.get("id")
    # 如果有id则进行数据查找
    if case_id:
        match = match_service.get(int(case_id))
        # 如果查询到结果
        if match:
            datas = [match.as_dict()]
            return {"code": 0, "msg": "获取数据成功", "data": datas}
        else:
            # 如果没有数据，则返回数据已存在
            return {"code": 40004, "msg": "数据已存在"}
    else:
        # 如果没有id,则返回全部数据
        datas = [match.as_dict() for match in match_service.list()]
        return {"code": 0, "msg": "获取数据成功", "data": datas}


@match_router.route("/match/post", methods=["POST"])
@jwt_required()
def match_post():
    """
    新增
    :return:
    """
    # 获取请求体
    data = request.json
    # 构造对象
    match = MatchModel(**data)
    # 新增
    id = match_service.create(match)
    if id:
        # 存在id, 则证明新增成功了
        return {"code": 0, "msg": "添加数据成功", "data": {"match_id": id}}
    else:
        return {"code": 40001, "msg": "数据已存在"}


@match_router.route("/match/put", methods=["POST"])
@jwt_required()
def match_put():
    """
    修改
    :return:
    """
    # 获取请求体
    data = request.json
    # 构造对象
    match = MatchModel(**data)
    # 修改
    id = match_service.update(match)
    if id:
        # 存在id, 则证明新增成功了
        return {"code": 0, "msg": "修改数据成功", "data": {"match_id": id}}
    else:
        return {"code": 40001, "msg": "修改数据失败"}


@match_router.route("/match/delete", methods=["POST"])
@jwt_required()
def match_delete():
    """
    测试用例的删除
    {"id": 1}
    :return:
    """
    # 获取请求体
    data = request.json
    delete_id = data.get("id")
    if delete_id:
        id = match_service.delete(delete_id)
        if id:
            # 存在测试用例id,则证明用例修改成功了
            return {"code": 0, "msg": f"删除数据成功", "data": {"match_id": id}}
        else:
            return {"code": 40001, "msg": "删除数据失败"}
